package main

import (
	"fmt"
	"github.com/samuel/go-zookeeper/zk"
	"log"
	"time"
)

//定义服务列表
var hosts = []string{"node01:2181", "node02:2181", "node03:2181"}
//路径
var path = "/test01"

var flags int32 = zk.FlagEphemeral
var data = []byte("hello xdl")

//定义为不控制权限
var acls = zk.WorldACL(zk.PermAll)

func main() {

	//设置监听回调
	option := zk.WithEventCallback(callback)

	//创建连接
	conn, _, err := zk.Connect(hosts, 5*time.Second, option)
	checkErr(err)

	//为path节点设置监听
	_, _, _, err = conn.ExistsW(path)

	checkErr(err)

	createNode(conn, path, data)

}

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
		return
	}
}

//回到用到的函数
func callback(event zk.Event) {

	//打印节点的状态
	fmt.Println("=================================")
	fmt.Println("path", event.Path)
	fmt.Println("type:", event.Type.String())
	fmt.Println("state:", event.State.String())
	fmt.Println("=================================")
}

func createNode(conn *zk.Conn, path string, data []byte) {
	//创建节点
	path, err := conn.Create(path, data, flags, acls)
	checkErr(err)
	fmt.Println("创建了新节点：", path)
}
